/**
 * Copyright (C) 2012-2013 jumei, Inc.
 * DefaultRouterHandler.java
 * 2015年6月26日
 */
package org.goface.rpc.pipeline;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.goface.rpc.MessageContext;

import com.goface.rpc.conf.DefaultServiceConfigureCenter;
import com.goface.rpc.conf.ServiceConfigure;
import com.goface.rpc.conf.ServiceConfigureCenter;
import com.google.common.net.HostAndPort;

/**
 *
 * @author jm110
 */
public class DefaultRouterHandler extends RouterHandler {
    ServiceConfigureCenter configureConter = DefaultServiceConfigureCenter.getInstance();
    private AtomicLong counter = new AtomicLong(0);

    private List<HostAndPort> resolveAdress(Object addressListConf) {
        String[] hostAndportArr = addressListConf.toString().split(",");
        List<HostAndPort> addressList = new LinkedList<>();
        for (String address : hostAndportArr) {
            HostAndPort one = HostAndPort.fromString(address);
            addressList.add(one);

        }
        return addressList;

    }

    /*
     * (non-Javadoc)
     *
     * @see org.goface.rpc.pipeline.RouterHandler#findServiceAddress(java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public HostAndPort findServiceAddress(MessageContext messageContext) {
        ServiceConfigure configure = configureConter.getServiceConfigure(messageContext.getClientServiceId());
        Object serviceAddressList = configure.getProperty(ServiceConfigure.SERVICE_CLIENT_SERVICE_ADDRESS);
        if (serviceAddressList == null) {
            throw new RuntimeException("lack of [service_address] within service bean configure :"
                    + messageContext.getClientServiceId());
        }
        List<HostAndPort> addressList = null;
        if (serviceAddressList instanceof String) {
            addressList = resolveAdress(serviceAddressList);
        } else {
            addressList = (List<HostAndPort>) serviceAddressList;
        }
        // 默认采用轮询
        return addressList.get((int) counter.getAndIncrement() % addressList.size());
    }
}
